package com.wnhz.work.jy.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.view.CircleImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * ----设置
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private TextView title;
    private final int FROM_NAME_CODE = 653;
    private static final int ACTIVITY_RESULT_FOR_UPDATE = 110;

    private CircleImageView iv_head;
    private Bitmap head;//头像Bitmap
    private static String path = "/sdcard/myHead/";//sd路径

    private TextView tv_name;
    private String newName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initData();
        initView();
    }

    private void initData() {

    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("设置");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.tv_exit).setOnClickListener(this);
        findViewById(R.id.rl_head).setOnClickListener(this);
        findViewById(R.id.rl_name).setOnClickListener(this);
        findViewById(R.id.rl_passWord).setOnClickListener(this);
        findViewById(R.id.rl_clean).setOnClickListener(this);
        findViewById(R.id.rl_grade).setOnClickListener(this);

        iv_head = (CircleImageView) findViewById(R.id.iv_head);
        tv_name = (TextView) findViewById(R.id.tv_name);

        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像，转换成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
            iv_head.setImageDrawable(drawable);
        } else {
            /**
             *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //修改头像
            case R.id.rl_head:
                showpopmwnu();
                break;

            //修改昵称
            case R.id.rl_name:
                String oldName = tv_name.getText().toString();
                intent = new Intent(SettingActivity.this, NicknameActivity.class);
                intent.putExtra("oldName", oldName);
                startActivityForResult(intent, FROM_NAME_CODE);
                break;

            //修改密码
            case R.id.rl_passWord:
                break;

            //清除缓存
            case R.id.rl_clean:
                break;

            //给我们打分
            case R.id.rl_grade:
                break;

            //退出
            case R.id.tv_exit:
                MyApplication.getInstance().userBean = null;
                MyApplication.getInstance().removerUser();
                MyApplication.getInstance().bean1 = null;
                MyApplication.getInstance().bean = null;
                intent = new Intent(SettingActivity.this, LoginActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private void showpopmwnu() {
        Intent selectPhotoIntent = new Intent(SettingActivity.this, SelectPhotoActivity.class);
        startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
//        startActivity(selectPhotoIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FROM_NAME_CODE:
                if (resultCode == RESULT_OK) {
                    newName = data.getExtras().getString("newName");
                    tv_name.setText(newName);
                }
                break;

            case ACTIVITY_RESULT_FOR_UPDATE:
                if (resultCode == RESULT_OK) {
                    String head1 = data.getStringExtra("head");
//                    System.out.println(head1 + "======head");
                    String from = data.getExtras().getString("from");
                    if ("1".equals(from)) {
//                        File t = new File(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "image");
//                        cropPhoto(Uri.fromFile(t));
                        ImageLoader.getInstance().displayImage("file://" + head1, iv_head);
                    } else {
                        File temp = new File(Environment.getExternalStorageDirectory()
                                + "/head.jpg");
                        cropPhoto(Uri.fromFile(temp));
                    }
                }
                break;

            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);//保存在SD卡中
                        iv_head.setImageBitmap(head);//用ImageView显示出来
                    }
                }
                break;

            default:
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        } finally {
//            try {
//                //关闭流
////                b.flush();
////                b.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }


}
